package cn.edu.gznu.wecampus.core.web;

import java.io.Serializable;

import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.edu.gznu.wecampus.core.ApplicationContextHolder;
import cn.edu.gznu.wecampus.core.JpaEntity;
import cn.edu.gznu.wecampus.core.service.PropertyService;
import cn.edu.gznu.wecampus.core.web.annotation.ApiPermissionConfig;

@Validated
public interface IEditRest<T extends JpaEntity<ID>, ID extends Serializable, FV extends FormVo<ID>> 
	extends IFormRest<T, ID, FV> {

	@SuppressWarnings("unchecked")
	@PostMapping(value = "/edit")
	@ApiPermissionConfig("edit")
	default RestResponseElement edit(@RequestBody String json) throws Exception {
		FV form = null;
		T entity = null;
		try {
			ObjectMapper mapper = new ObjectMapper();
			form = mapper.readValue(json, this.getFormVoClass());
			ID id = form.getId();
			entity = getRepository().findOne(id);
		} catch(Exception e) {
			throw new RestException(e);
		}
		if(entity == null) {
			PropertyService propertyService = ApplicationContextHolder.getBean(PropertyService.class);
			throw new RestException(
				propertyService.getProperty("pointcircle.framework.message.object-not-exist")
			);
		}
		IEditRest<T, ID, FV> self = (IEditRest<T, ID, FV>) this.getSelfComponent();
		self.processEditEntity(form, entity);
		return this.createRestResponseElement(entity);
	}
	
	void processEditEntity(@Valid FV form, T entity) throws Exception;
}
